# -*- encoding: utf-8 -*-
'''
@File    :   log_plot.py
@Time    :   2023/08/02
@Author  :   Han Xiao
@Brief   :   根据提供的关键字绘制折线图
'''
import re
import argparse
from datetime import datetime
import matplotlib.pyplot as plt
import random

# 定义命令行参数(LOG文件路径 & 解析关键字)
parser = argparse.ArgumentParser()
parser.add_argument('-k','--keys', nargs='+', help='关键字列表 有空格 分割，使用引号,如果包含冒号，将冒号也搞过来')
parser.add_argument('-l','--log', help='LOG 文件路径，使用绝对路径吧')
parser.add_argument('-f','--format', default=1, help='默认为1表示原智耘log格式, 2表示新智耘格式' )
args = parser.parse_args()

if args.keys:
    key_msgs = args.keys
    if len(key_msgs) == 1:
        key_msgs.append(key_msgs[0])
else:
    parser.print_help()
    exit()

if args.log:
    log_path = args.log
else:
    parser.print_help()
    exit()

log_format = int(args.format)

# 关键字列表 有空格，如果包含冒号，将冒号也搞过来
# key_msgs = ['real_speed', 'set_target_imple:','forecast_radar_flag:']

# 定义正则表达式，用于匹配时间
time_pattern = re.compile(r'[IDE](\d{2})(\d{2}) (\d{2}):(\d{2}):(\d{2}).(\d{3}) (\d+) ')
if log_format == 2:
    time_pattern = re.compile(r'\[(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d{3})\]')
if log_format == 3:
    time_pattern = re.compile(r'(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d{3})')

# 定义正则表达式，用于匹配关键信息（数字 or true or false）
patterns = []
for key_msg in key_msgs:
    # pattern_key_msg = r'{}\s+([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?|true|false)'.format(key_msg)
    pattern_key_msg = r'{}\s*=?\s*([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?|true|false)'.format(key_msg)
    patterns.append(re.compile(pattern_key_msg))

# 打开log文件
with open(log_path, 'r') as f:
    lines = f.readlines()

# 初始化时间和关键信息列表
times = [[] for _ in range(len(key_msgs))]
key_info = [[] for _ in range(len(key_msgs))]

# 遍历每一行log信息
for line in lines:
    # 匹配时间和关键信息
    time_match = time_pattern.match(line)
    for i, pattern in enumerate(patterns):
        key_info_match = pattern.search(line)
        if time_match and key_info_match:
            # 提取时间和关键信息
            if log_format == 2:
                year = int(time_match.group(1))
                month = int(time_match.group(2))
                day = int(time_match.group(3))
                hour = int(time_match.group(4))
                minute = int(time_match.group(5))
                second = int(time_match.group(6))
                millisecond = int(time_match.group(7))
            elif log_format == 1:
                year = 2024
                month = int(time_match.group(1))
                day = int(time_match.group(2))
                hour = int(time_match.group(3))
                minute = int(time_match.group(4))
                second = int(time_match.group(5))
                millisecond = int(time_match.group(6))
            elif log_format == 3:
                year = int(time_match.group(1))
                month = int(time_match.group(2))
                day = int(time_match.group(3))
                hour = int(time_match.group(4))
                minute = int(time_match.group(5))
                second = int(time_match.group(6))
                millisecond = int(time_match.group(7))
            time = datetime(year, month, day, hour, minute, second, millisecond * 1000)

            key_info_value = key_info_match.group(1)
            # 非数字信息处理 
            if key_info_value == 'true':
                key_info_value = 1
            elif key_info_value == 'false':
                key_info_value = 0
            else:
                key_info_value = float(key_info_value)
            
            times[i].append(time)
            key_info[i].append(key_info_value)

# 绘制折线图
fig, axs_line = plt.subplots(len(key_msgs), 1, figsize=(8, 6 * len(key_msgs)), sharex='col')
# 绘制散点图
fig, axs_scatter = plt.subplots(len(key_msgs), 1, figsize=(8, 6 * len(key_msgs)), sharex='col')
for i in range(len(key_msgs)):
    x_values = list(range(1, len(key_info[i]) + 1)) # 如果时间戳一致，使用x_valuse将点区分开
    axs_line[i].plot(times[i], key_info[i],marker='o', markersize=2)
    axs_scatter[i].scatter(times[i], key_info[i])

    axs_line[i].set_xlabel('Time')
    axs_line[i].set_ylabel(key_msgs[i])
    axs_line[i].grid(True)
    axs_scatter[i].set_xlabel('Time')
    axs_scatter[i].set_ylabel(key_msgs[i])
    axs_scatter[i].grid(True)
    

# 共轴图按需打开
# 绘制共轴图（轴分离）
# fig, ax = plt.subplots(figsize=(8, 6))
# colors = [f'#{random.randint(0, 0xFFFFFF):06x}' for _ in range(len(key_msgs))]

# for i, key_msg in enumerate(key_msgs):
#     # 创建新的y轴
#     ax_new = ax.twinx()
#     ax_new.plot(times[i], key_info[i], color=colors[i], label=key_msg)
#     # 调整位置
#     ax_new.spines['right'].set_position(('axes', 1 + (i * 0.03)))
#     ax_new.set_ylabel(key_msg, color=colors[i])

#     ax_new.tick_params(axis='y', labelcolor=colors[i],pad=0)
#     # ax_new.grid(True)
#     # ax_new.legend(loc='upper left')

# ax.set_xlabel('Time')
# fig.legend(loc='upper left')


# # 绘制共轴图（共轴）
# 折线形式
fig, ax = plt.subplots(figsize=(8, 6))
# 散点形式
fig, ax_scatter = plt.subplots(figsize=(8, 6))
colors = [f'#{random.randint(0, 0xFFFFFF):06x}' for _ in range(len(key_msgs))]

labels = []
for i, key_msg in enumerate(key_msgs):
    x_values = list(range(1, len(key_info[i]) + 1)) # 如果时间戳一致，使用x_valuse将点区分开
    ax_scatter.scatter(times[i], key_info[i], color=colors[i], label=key_msg) # 散点图
    ax.plot(times[i], key_info[i], color=colors[i], label=key_msg, marker='o', markersize=2) #折线
    # ax.tick_params(axis='y', labelcolor=colors[i],pad=0)

ax.grid(True)
ax_scatter.grid(True)
ax.set_xlabel('Time')
ax_scatter.set_xlabel('Time')
ax.legend(loc='upper left')
ax_scatter.legend(loc='upper left')

plt.show()
